﻿using Domain.QualityInspection_Modelling;
using Infratructure;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler.NewQualityInspectionCommandHandler
{
    public class DeleteQualityInspectionHandlers : IRequestHandler<DeleteQualityInspectionCommands, ApiResult<object>>
    {
        private readonly IRepository<QualityInspection> _qualityRepo;
        private readonly DateContext _dbContext;

        public DeleteQualityInspectionHandlers(
            IRepository<QualityInspection> qualityRepo,
            DateContext dbContext)
        {
            _qualityRepo = qualityRepo;
            _dbContext = dbContext;
        }

        public async Task<ApiResult<object>> Handle(DeleteQualityInspectionCommands request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<object>();

            var inspection = await _qualityRepo.GetValue(request.Id);
            if (inspection == null)
                return result.Fail("质检记录不存在");

            _dbContext.Set<QualityInspection>().Remove(inspection);
            var dbResult = await _dbContext.SaveChangesAsync(cancellationToken);

            return dbResult > 0
                ? result.Success("质检记录删除成功", null)
                : result.Fail("质检记录删除失败");
        }
    }
}
